package cn.life.bootstap;


import cn.life.common.push.PushConfiguration;
import cn.life.common.support.handler.HttpServletRequestReplacedFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.util.Log4jConfigListener;

import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;


/**
 * @Description:    启动入口
 *
 * @Author 李佳明
 * @Date 2018/5/2 11:54
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer{

    @Override
    public void onStartup(ServletContext servletContext)  throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

        //启动基础配置
        rootContext.register(MySpringMvcConfiguration.class);
        rootContext.register(PushConfiguration.class);

        //上下文监听
        servletContext.addListener(new ContextLoaderListener(rootContext));
        servletContext.setInitParameter("log4jConfigLocation","/WEB-INF/classes/log4j.properties");
        servletContext.addListener(new Log4jConfigListener());

        //加入编码过滤器
        servletContext.addFilter("encodingFilter", encodingFilter()).addMappingForUrlPatterns(null, false, "/*");
        servletContext.addFilter("requestFilter",HttpServletRequestReplacedFilter.class).addMappingForUrlPatterns(null, false, "/*");

        //Spring Requset 监听器
        servletContext.addListener(new RequestContextListener());

        //springmvc上下文
        //rootContext.register(MySpringMvcConfiguration.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        dynamic.setLoadOnStartup(2);
        dynamic.addMapping("/");
    }

    private Filter encodingFilter() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        return filter;
    }

}
